﻿using BasicInformation.ApiRead.Application.Command.Category;
using BasicInformation.Dtos;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using Dapper;
using MediatR;
using System.Text;

namespace BasicInformation.ApiRead.Application.Handler.Category
{
    public class GetCategoryHandler : IRequestHandler<GetCategoryCommand, ApiPaging<CategoryDTO>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<GetCategoryHandler> logger;

        public GetCategoryHandler(DatabaseContext db,ILogger<GetCategoryHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiPaging<CategoryDTO>> Handle(GetCategoryCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<CategoryDTO> result = new ApiPaging<CategoryDTO>();
            StringBuilder sql = new StringBuilder();
            StringBuilder countSql = new StringBuilder();

            // 主查询SQL - 获取分类及其父级分类信息
            sql.Append(@"SELECT 
                        a.CategoryId,
                        a.CategoryCode,
                        a.CategoryName,
                        a.CategoryParent,
                        b.CategoryId AS ParentCategoryId,
                        b.CategoryName AS ParentCategoryName,
				                a.CategoryRemark
                    FROM 
                        categorymodel a
                    LEFT JOIN 
                        categorymodel b ON a.CategoryParent = b.CategoryId
                    WHERE 
                        a.IsDel = 0"); 

            // 计数SQL - 只查询总记录数
            countSql.Append(@"SELECT COUNT(*) 
                            FROM categorymodel a
                            WHERE a.IsDel = 0");

            // 添加查询条件 - 分类编号精确查询
            if (!string.IsNullOrWhiteSpace(request.CategoryCode))
            {
                sql.Append(" AND a.CategoryCode = @CategoryCode");
                countSql.Append(" AND a.CategoryCode = @CategoryCode");
            }

            // 添加查询条件 - 分类名称模糊查询
            if (!string.IsNullOrWhiteSpace(request.CategoryName))
            {
                sql.Append(" AND a.CategoryName LIKE @CategoryName");
                countSql.Append(" AND a.CategoryName LIKE @CategoryName");
            }

            // 添加排序和分页
            sql.Append(" ORDER BY a.CategoryId DESC LIMIT @size OFFSET @offset");

            // 设置参数
            var parameters = new
            {
                CategoryCode = request.CategoryCode,
                CategoryName = string.IsNullOrEmpty(request.CategoryName) ? null : $"%{request.CategoryName}%",
                size = request.size,
                offset = (request.index - 1) * request.size
            };
            try
            {
                // 执行查询
                var pageData = await db.DapperConnection.QueryAsync<CategoryDTO>(sql.ToString(), parameters);
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.size);

                // 设置返回结果
                result.Msg = "分类查询成功";
                result.Code = ApiEnum.OK;
                result.Data = pageData.ToList();
                result.TotalCount = totalCount;
                result.TotalPCount = totalPage;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "分类查询失败");
                result.Code = ApiEnum.Fail;
                result.Msg = "分类查询失败";
            }

            return result;
        }
    }
}
